<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+ postForm.status">

        <el-button v-loading="loading" style="margin-left: 10px;float:left;margin-top: 5px;" type="primary"  @click="goBack">
          返回
        </el-button>

        <!-- v-model 对子组件数据双向绑定 -->
        <CommentDropdown v-model="postForm.commentDisabled" />
        <!--<PlatformDropdown v-model="postForm.platforms" />-->
        <!--<SourceUrlDropdown v-model="postForm.sourceUrl" />-->

        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          {{ isEdit ? '保存':'发布'}}
        </el-button>

        <el-button v-loading="loading" type="warning" @click="draftForm">
          保存草稿
        </el-button>

        <el-button v-if='isEdit' v-loading="loading" type="danger" @click="deleteForm">
          删除
        </el-button>

      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput style="width:500px;" v-model="postForm.title" :maxlength="100" name="name" required>
                标题
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" label="发布者:" class="postInfo-container-item">
                    <el-input v-model="postForm.author" style="width:200px;" prefix-icon="el-icon-document"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label-width="120px" label="时间:" class="postInfo-container-item">
                    <el-date-picker v-model="display_Time" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="Select date and time" />
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="90px" label="Importance:" class="postInfo-container-item">
                    <el-rate
                      v-model="postForm.importance"
                      :max="3"
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      :low-threshold="1"
                      :high-threshold="3"
                      style="display:inline-block"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="简介:">
          <el-input v-model="postForm.contentShort" :rows="1" type="textarea" class="article-textarea" autosize placeholder="Please enter the content" />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item>

        <el-form-item prop="详细内容" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item>

        <!--图片上传-->
        <!--<el-form-item prop="imageUri" style="margin-bottom: 30px;">-->
          <!--<Upload v-model="postForm.imageUri" />-->
        <!--</el-form-item>-->

      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
// import Upload from '@/components/Upload/SingleImage3'  // 图片上传
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
import { fetchArticle , createArticle , updateArticle} from '@/api/article'
import { CommentDropdown, PlatformDropdown, SourceUrlDropdown } from './Dropdown'
import { parseTime } from '@/utils'
import { mapGetters } from 'vuex'


const defaultForm = {
  status: 'draft',
  title: '',
  content: '',
  contentShort: '',
  sourceUrl: '', // 文章外连接
  imageUri: '',
  displayTime: undefined,
  id: undefined,
  platforms: 'a-platform',
  commentDisabled: 0,
  importance: 1
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Sticky, CommentDropdown, PlatformDropdown, SourceUrlDropdown },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback()
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          })
          callback(new Error('外链url填写不正确'))
        }
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        imageUri: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        sourceUri: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      tempRoute: {}
    }
  },
  computed: {
    ...mapGetters([
      'authName',
      'roles'
    ]),

    contentShortLength() {
      if(this.postForm.contentShort==null){
        return 0;
      }else{
        return this.postForm.contentShort.length
      }
    },

    // v-model 绑定日期选择框,改变时改变postForm.displayTime
    display_Time: {
      get() {
        return (+new Date(this.postForm.displayTime))
      },
      set(val) {
        this.postForm.displayTime = parseTime(new Date(val))
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchData(id) {
      fetchArticle(id).then(response => {
        this.postForm = response.data
        // set page title
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },

    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.postForm.id}`
    },

    submitForm() {
      this.postForm.status = 'published',
      this.postForm.timestamp=(new Date()).valueOf()/1000
      if (this.isEdit){
        updateArticle(this.postForm).then(response => {
          this.$notify({
            title: '保存成功',
            message: response.errmsg,
            type: 'success',
            duration: 2000
          })
          this.fetchData(id)
        }).catch(err => {
          console.log(err)
        })
      }else{
        createArticle(this.postForm).then(response => {
          this.$notify({
            title: '添加成功',
            message: response.errmsg,
            type: 'success',
            duration: 2000
          })
          this.$router.push({path:'/files/list'})
        }).catch(err => {
          console.log(err)
        })
      }

    },

    draftForm() {
      if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }

      this.postForm.status = 'draft'
      this.postForm.timestamp=(new Date()).valueOf()/1000
      if (this.isEdit){
        updateArticle(this.postForm).then(response => {
          this.$notify({
            title: '保存成功',
            message: response.errmsg,
            type: 'success',
            duration: 2000
          })
          this.fetchData(id)
        }).catch(err => {
          console.log(err)
        })
      }else{
        createArticle(this.postForm).then(response => {
          this.$notify({
            title: '添加成功',
            message: response.errmsg,
            type: 'success',
            duration: 2000
          })
          this.$router.push({path:'/files/list'})
        }).catch(err => {
          console.log(err)
        })
      }
    },

    deleteForm(){
      this.postForm.status = 'deleted'
      this.postForm.commentDisabled = 1
      updateArticle(this.postForm).then(response => {
        this.$notify({
          title: '删除成功',
          message: response.errmsg,
          type: 'success',
          duration: 2000
        })
        this.fetchData(id)
      }).catch(err => {
        console.log(err)
      })
    },


    goBack(){
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
